<template>
  <el-card class="introduce mt-20 mr-20" shadow="never">
    <el-form :disabled="permissionDisabled()" :model="dialogForm" :rules="rules" ref="goodRef" label-position="top" class="form-readonly">
      <el-form-item :label="$t('pageStr.timeZoneStr')">
        <el-select v-model="dialogForm.timeZone" style="width:215px;">
          <el-option v-for="item in $tm('timeZoneStr')" :label="item.country" :value="item.encoded"/>
        </el-select>
        <el-button style="margin-left: 25px;width: 110px;" type="primary" @click="handleSubmitTimeZone">
          {{ $t('tabsStr.applyStr') }}
        </el-button>

      </el-form-item>
      <el-form-item :label="$t('menuStr.setTimeStr')">
        <el-config-provider :locale="zhCn">
          <el-date-picker v-model="dialogForm.date" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
        </el-config-provider>
        <el-button style="margin-left: 20px;width: 110px;" type="primary" @click="handleSubmitSysDate">
          {{ $t('tabsStr.applyStr') }}
        </el-button>
      </el-form-item>
      <el-form-item :label="$t('menuStr.timeSynStr')">
        <div class="readonly__wrap" style="width: 260px;">{{ $t('pageStr.localTimeStr') + ' : ' + localTime }}</div>
        ······
        <div class="readonly__wrap" style="width: 260px; color: #C29561">
          {{ $t('pageStr.deviceTimeStr') + ' : ' + dialogForm.deviceTime }}
        </div>
        <el-button style="margin-left: 20px;width: 110px;color: #C29B74;" @click="handleSycnDeviceTime">
          {{ $t('tabsStr.syncStr') }}
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card class="mt-10 mr-20" shadow="never">
    <el-form :disabled="permissionDisabled()" :model="ntpForm" label-width="200px" label-position="left">
      <el-form-item :label="$t('pageStr.enableNtpClientStr')">
        <el-switch v-model="ntpForm.enabled" active-color="#C29561" active-value="1" inactive-value="0"></el-switch>
      </el-form-item>
      <div v-if="ntpForm.enabled == '1'">
        <el-form-item :label="$t('pageStr.ntpClientCycleStr')" style="max-width: 500px">
          <el-select v-model="ntpForm.cycle" style="width: 100%;" clearable>
            <el-option label="1 min" value="1"></el-option>
            <el-option label="5 min" value="5"></el-option>
            <el-option label="20 min" value="20"></el-option>
          </el-select>
        </el-form-item>
        <template v-for="item of ntpForm.server.length">
          <el-form-item :label="$t('pageStr.proNtpServertStr')+'_'+item" style="max-width: 500px">
            <el-input v-model="ntpForm.server[item - 1]" :maxlength="15">
              <template #suffix>
                <el-icon v-permissionShow v-if="ntpForm.server.length > 1" color="#E06363" :size="20" style="cursor: pointer"
                         @click="delIpRow(item,ntpForm.server)">
                  <CloseBold/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
        </template>
        <div v-if="ntpForm.server.length < 8" style="max-width: 300px; margin-left: 200px">
          <el-button style="width: 100%; " @click="addIp(ntpForm.server)">
            <el-icon>
              <Plus/>
            </el-icon>
          </el-button>
        </div>
      </div>
    </el-form>
  </el-card>
  <el-button v-permissionShow style="margin-top: 20px;width: 110px;color: #fff" color="#C29B74" @click="handleSubmitNtp">
    {{ $t('tabsStr.applyStr') }}
  </el-button>

</template>

<script setup>
import {onMounted, reactive, ref, onBeforeUnmount} from "vue";
import {dateFormat,permissionDisabled} from '@/utils'
import zhCn from 'element-plus/lib/locale/lang/zh-cn'
import {useI18n} from 'vue-i18n'
import {ElMessage} from "element-plus";
import {
  reqGetSyncTime,
  reqGetSysTime,
  reqSetSyncTime,
  reqSetSysTime,
  reqSetTimeZone
} from "@/api/application/time-sycn";

const {t, tm} = useI18n()
let localTime = ref(dateFormat(Date.now()))
let timer = null
const dialogForm = ref({})
const ntpForm = ref({
  server: ['']
})
const rules = reactive({})
onMounted(() => {
  reqGetSyncTime().then((res) => {
    ntpForm.value = res.syncTime
    ntpForm.value.server = res.syncTime.server || ['']
    console.log('回显sync', ntpForm.value)
  })
  reqGetSysTime().then((res) => {
    // console.log('系统时间，', res)
    dialogForm.value.deviceTime = res.sysTimeInfo[0]
    dialogForm.value.timeZone = res.sysTimeInfo[1]
  })
  timer = setInterval(getData, 1000)
})

/**
 * 设置时区
 */
function handleSubmitTimeZone() {
  console.log('选择时区', dialogForm.value.timeZone)
  reqSetTimeZone({timezone: dialogForm.value.timeZone}).then(() => {
    ElMessage.success(t('successTip'))
  }).catch(() => {
    ElMessage.error(t('errorTip'))
  })
}

function getData() {
  localTime.value = dateFormat(Date.now())
  reqGetSysTime().then((res) => {
    // console.log('系统时间，', res)
    dialogForm.value.deviceTime = res.sysTimeInfo[0]
  })
}

/**
 * 同步设备时间
 */
function handleSycnDeviceTime() {
  reqSetSysTime({date: localTime.value}).then(() => {
    ElMessage.success(t('successTip'))
  }).catch(() => {
    ElMessage.error(t('errorTip'))
  })
}

function handleSubmitSysDate() {
  if (!dialogForm.value.date) {
    console.log('日期未选择，不操作')
    return
  }
  reqSetSysTime({date: dialogForm.value.date}).then(() => {
    ElMessage.success(t('successTip'))
  }).catch(() => {
    ElMessage.error(t('errorTip'))
  })
}

function handleSubmitNtp() {
  const submitForm = {
    enabled: ntpForm.value.enabled,
    cycle: ntpForm.value.cycle
  }
  let i = 0
  ntpForm.value.server.forEach((item) => {
    submitForm['server' + i] = item
    i++
  })
  submitForm.num = i
  console.log('新增数据，', submitForm)
  reqSetSyncTime(submitForm).then(() => {
    ElMessage.success(t('successTip'))
  }).catch(() => {
    ElMessage.error(t('errorTip'))
  })
}

function addIp(ipArr) {
  if (ipArr.length > 7) {
    ElMessage.warning('最大支持8个IP')
    return
  }
  ipArr.push('')
}

function delIpRow(rowId, ipArr) {
  ipArr.splice(rowId - 1, 1)
}

onBeforeUnmount(() => {
  timer && clearInterval(timer)
})
</script>

<style scoped>
.introduce .order {
  display: flex;
  margin-bottom: 50px;
}

.introduce .order .order-item {
  flex: 1;
  margin-right: 20px;
}

.introduce .order .order-item:last-child {
  margin-right: 0;
}

#zoom {
  min-height: 300px;
}
</style>